package main

import (
	"fmt"
	"os"
	"strings"
)

// 检出环境
func handleCheckout(args []string) {
	if len(args) == 0 {
		fmt.Println("请指定环境名称")
		fmt.Println("用法: genv checkout <环境名>")
		os.Exit(1)
	}

	targetEnv := args[0]
	fmt.Println("正在准备干净的工作区...")
	if err := hardReset(); err != nil {
		fmt.Printf("工作区清理失败: %v\n", err)
		os.Exit(1)
	}

	output, err := runGit("stash", "list")
	if err != nil {
		fmt.Printf("环境查询失败: %v\n", err)
		return
	}

	var targetIndex string
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		parts := strings.SplitN(line, ": ", 3)
		if len(parts) >= 3 && parts[2] == targetEnv {
			indexPart := strings.Split(parts[0], " ")[0]
			targetIndex = strings.TrimPrefix(indexPart, "stash@{")
			targetIndex = strings.TrimSuffix(targetIndex, "}")
			break
		}
	}

	if targetIndex == "" {
		fmt.Printf("未找到环境: %s\n", targetEnv)
		return
	}

	_, err = runGit("stash", "apply", fmt.Sprintf("stash@{%s}", targetIndex))
	if err != nil {
		fmt.Printf("环境应用失败: %v\n", err)
		return
	}
	fmt.Printf("已应用环境: %s\n", targetEnv)
}
